<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function array(nums) {
      //max表示前i个元素以k结尾的最大余数和
      const n = nums.length
      var max = [-Infinity, -Infinity, -Infinity]
      max[nums[0] % 3] = nums[0]
      for (var i = 1; i < n; i++) {
        const k = nums[i] % 3
        //tmp表示以nums[i]结尾的子序列的最大和
        const dp = [-Infinity, -Infinity, -Infinity]
        dp[k] = nums[i] //不与前面的数连接可以构成子序列
        for (let r = 0; r <= 2; r++) dp[r] = Math.max(dp[r], max[(r + 3 - k) % 3] + nums[i])
        //捕捉最大的子序列
        for (let r = 0; r <= 2; r++) max[r] = Math.max(max[r], dp[r])
      }
      return max[0] === -Infinity ? 0 : max[0]
    };
    console.log(array([3, 6, 5, 1, 8]));
  </script>
</body>

</html>